let JWT = require("../config/jwt.js").JWT
//拦截token验证
function tokenInterceptor(app){
  app.use('*', function(request, response, next) {
    //请求路径名称
    let pathname = request._parsedUrl.pathname
    //如果是登录或注册，不需要拦截token
    if(pathname==='/users/login'|| pathname==="/users/register"||pathname==="/"){
      return  next()
    }
    //获得请求头
    let headers = request.headers
    //获得请求头中的token
    let token = headers.authorization
    console.log(token)
    //没有携带token,让用户进行登录，获取token
    if (!token) {
      return response.send('请先登录')
    }
    //执行token验证，如果验证的结果是err,说明token不正确
    let jwt = new JWT(token)
    if (jwt.verifyToken() === 'err') {
      return response.send('请重新登录')
    }
    next()
  })
}

exports.tokenInterceptor = tokenInterceptor